package com.jch.po.codec;

import com.jch.po.util.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

// 对象编码器
public class ObjEncoder extends MessageToByteEncoder {

    private Class<?> genericClass;

    public ObjEncoder(Class<?> genericClass) {
        this.genericClass = genericClass;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        if (genericClass.isInstance(msg)){ // 检查是否该消息类型对象
            byte[] data = SerializationUtil.serialize(msg); // 将对象转换为byte数组
            out.writeInt(data.length); // 写入int型数据
            out.writeBytes(data);
        }
    }
}
